package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepsitory;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepsitory repsitory;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        repsitory.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repsitory.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repsitory.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo userInfo = repsitory.findByPhone(phone);
        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone) {

        //创建验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-", "")
                .substring(0, 4);

        //创建短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("【叩丁狼】您注册的短信验证码是:").append(code).append(", 请在")
                .append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟内使用");


        //假装短信已经发送
        System.out.println(sb);

        //真实发送短信本质就是使用java发起http请求即可
        //Springmvc提供一个工具类:RestTemplate 用于发起http请求
        RestTemplate template = new RestTemplate();

        //参数1: 短信接口url

        //https://way.jd.com/BABO/sms?mobile=15000000000&msg=【巴卜技术】您的验证码是201422,若非本人操作请忽略&appkey=dd1f7d99cd632060789a56cfaa3b77ce
        //String url = "https://way.jd.com/BABO/sms?mobile={1}&msg={2}&appkey={3}";
        //参数2: 请求接口完之后相应数据封装对象类型
        //参数3: 请求参数列表
        //String ret = template.getForObject(url, String.class, phone, sb.toString(), "dd1f7d99cd632060789a56cfaa3b77ce");
       // System.out.println(ret);

       // if(!ret.contains("Success")){
            //throw new LogicException("短信发送失败");
        //}

        //将验证码缓存到redis中
        userInfoRedisService.setVerifyCode(phone, code);
    }


    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //校验参数是否为空
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //校验2次输入密码是否相等
        AssertUtil.isEquals(password, rpassword, "两次输入密码不一致");
        //校验手机号码是否正确 @TODO java 的正则表达式
        //校验手机号码是否唯一
        if(this.checkPhone(phone)){
            throw new LogicException("该手机号码已经被注册");
        }
        //校验短信验证码是否正确
        String code = userInfoRedisService.getVerifyCode(phone);
        if(!verifyCode.equalsIgnoreCase(code)){
            throw  new LogicException("验证码无效获取错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);  //假装加密
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setInfo("");
        userInfo.setHeadImgUrl("/images/default.jpg");

        //核心属性必须自己控制
        userInfo.setState(UserInfo.STATE_NORMAL);


        //模拟一个系统级别(一些环境或者代码bug造成异常)
        //throw new RuntimeException("假设这个是一个异常 l.sjdfsjdkfjksdjfkjskdfjksdjfksdkfksdjfklsjkd" +
                //"fjskdljflksjdfljsdkfjdsjfsjfkjskfjakljlkdssdkfjskdjfksjdkfjsd");
        this.save(userInfo);

    }

    @Override
    public UserInfo login(String username, String password) {

        //UserInfo user = repsitory.findByPhoneAndPassword(username, password);
        UserInfo user = repsitory.findByPhone(username);

        if(user == null || !user.getPassword().equals(password)){
            throw  new LogicException("账号或密码错误");
        }
        user.setPassword("");
        return user;
    }

    @Override
    public List<UserInfo> queryByCity(String destName) {
        return repsitory.findByCity(destName);
    }
}
